// <copyright file="SettingsController.cs" company="Clever Software">
// Copyright (c) 2013, 2014 All Right Reserved, http://www.cleversoftware.by
//
// This source is subject to the Microsoft Permissive License.
// Please see the License.txt file for more information.
// All other rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// </copyright>
// <author>Clever Software</author>
// <email>info@cleversoftware.by</email>
// <date>2014-02-04</date> 
// <summary>CleverCMS source code</summary>

namespace CleverCMS.Web.Cms.Admin.Controllers
{

    using System;
    using System.Linq;
    using System.Web.Mvc;
    using System.Collections.Generic;

   // using Common.Logging;
    using CleverCMS.Cms.Data.Entities;
    using CleverCMS.Cms.Services;
    using CleverCMS.Core.Services;

    [Authorize(Roles = "Admin")]
    public class SettingsController : Controller
    {
        private readonly SettingService     m_settingService;
        private readonly LoggingService     m_loggingService;

        public SettingsController(SettingService settingService, 
                                  LoggingService loggingService)
        {
            this.m_settingService = settingService;
            this.m_loggingService = loggingService;
        }

        public ActionResult List()
        {
            return View();
        }

        [HttpPost]
        public JsonResult ListSettings(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
        {
            try
            {
                int count = 0;
                IEnumerable<CmsSetting> allPages = m_settingService.LoadAll(jtStartIndex, jtPageSize, jtSorting, out count).ToList();
                return Json(new { Result = "OK", Records = allPages, TotalRecordCount = count });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        public ViewResult Edit(int? id)
        {
            if (id == null) return View(new CmsSetting());
            var attr = m_settingService.Load(id.Value);
            return View(attr ?? new CmsSetting());
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Edit(CmsSetting attr)
        {
            if (ModelState.IsValid)
            {
                if (attr!=null)
                {
                    m_settingService.Update(attr);
                    m_loggingService.Info("Widget saved.");
                    return Json(new { success = true, error = "", id = attr.Id });
                }
                else
                    return Json(new { success = false, error = "Unknown error" });
            }
            else
            {
                var errorsList = ModelState.Values.SelectMany(x => x.Errors);
                var errorMessage = errorsList.Aggregate("", (current, modelError) => current + (modelError.ErrorMessage + "<br />"));
                return Json(new { success = false, error = errorMessage });
            } 
        }

        [HttpPost]
        [Authorize]
        public ActionResult Delete(int? Id)
        {
            if (!ModelState.IsValid)
                return Json(new { Result = "ERROR", Message = "", success = false, error = "Unknown error" });
         
            try
            {
                if (Id != null)
                {
                    m_settingService.Delete(Id.Value);
                    m_loggingService.Warn("Widget deleted.");
                    return Json(new { Result = "OK", Message = "", success = true, error = "", settingId = Id });
                }
                else
                    return Json(new { Result = "ERROR", Message = "", success = false, error = "Unknown error" });
            }
            catch (Exception exc)
            {
                var v = new { Result = "ERROR", Message = exc.Message, success = false, error = exc.Message };
                return Json(v);
            }
        }
    }
}